package com.thenie.chat.rabbitmq;

import com.thenie.chat.config.RabbitmqConfig;
import com.thenie.chat.pojo.AddRequest;
import com.thenie.chat.service.IAddRequestService;
import com.thenie.chat.util.WebSocketUtil;
import com.thenie.chat.vo.FriendRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

import static com.thenie.chat.controller.DialogSocketHandler.SESSION_MAP;

/**
 * @Description 队列消费者
 * @Author thenie
 * @Data 2022/6/5 12:45
 */
@Component
@Slf4j
public class AddRequestConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IAddRequestService addRequestService;



    /**
     * 更新好友请求记录
     * @param friendRequestVo
     */
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_ADD_REQUEST_SAVE})
    public void saveAddReq(FriendRequestVo friendRequestVo) {
        //判断数据库中是否存在
        AddRequest q1 = addRequestService.queryAddRequestFromMe(friendRequestVo.getFromId(), friendRequestVo.getToId());
        if (q1==null){//不存在，插入记录
            addRequestService.insertRequest(friendRequestVo.getFromId(),friendRequestVo.getToId(),friendRequestVo.getSign());
        }else{//存在修改标志
            addRequestService.updateSign(new AddRequest(null,friendRequestVo.getFromId(),friendRequestVo.getToId(),null,0));
        }
    }

    /**
     * 发送、通知好友请求消息
     * @param friendRequestVo
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_ADD_REQUEST_SEND})
    public void sendInform(FriendRequestVo friendRequestVo) throws IOException {
        FriendRequestVo fr = new FriendRequestVo();

        Long toId = friendRequestVo.getToId();
        //判断是否在线
        if (SESSION_MAP.containsKey(toId.toString())){//在线
            //通知对方
            WebSocketSession webSocketSession = SESSION_MAP.get(toId.toString());
            WebSocketUtil.sendFriendRequest(webSocketSession,friendRequestVo);
        }

    }


}
